﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;


namespace Synchros
{
    public partial class FrmServer : Form
    {
        public FrmServer()
        {
            InitializeComponent();
        }
        private bool isSyncStart;
        public FrmServer(bool isSyncStart)
        {
            this.isSyncStart = isSyncStart;

            InitializeComponent();
        }

        #region 全局变量
        /// <summary>
        /// 定时计数器
        /// </summary>
        private int iTimerCount = 0;

        /// <summary>
        /// 测试连接是否通过
        /// </summary>
        private bool isTestConnApproved = false;

        /// <summary>
        /// 测试连接是否完成
        /// </summary>
        private bool isTestConnCompleted = false;
        /// <summary>
        /// 当前服务器配置
        /// </summary>
        private DataTable dtGlobalServer = new DataTable();


        private string strServer;
        private string strUserID;
        private string strPassword;//记得加密数据库密码

        #endregion 全局变量
        /// <summary>
        /// 服务器配置 保存事件
        /// </summary>
        private void btnServerSave_Click(object sender, EventArgs e)
        {
            groupBox1.Enabled = false;
            // 得到连接信息
            {
                strServer = cbxServer.Text.Trim();
                if (strServer == "")
                {
                    MessageBox.Show("服务器不能为空！");
                    cbxServer.Focus();
                    groupBox1.Enabled = true;
                    return;
                }
                strUserID = txtUserID.Text.Trim();
                if (strUserID == "")
                {
                    MessageBox.Show("用户名不能为空！");
                    lblUserID.Focus();
                    groupBox1.Enabled = true;
                    return;
                }
                strPassword = Cryptogram.Encrypt(txtPassword.Text);//加密数据库密码
            }

            // 调用进度条
            progressBarTestConnication.Visible = true;
            //开启定时刷新进度条
            timer1.Enabled = true;

            // 开辟线程测试连接
            Thread threadTestConn = new Thread(new ThreadStart(TestConnectionWork));
            threadTestConn.Start();
        }

        /// <summary>
        /// 测试连接工作线程
        /// </summary>
        private void TestConnectionWork()
        {
            // 调用方法测试数据库连接
            string strMsg = SqlHelper.TestConnection(strServer, strUserID, strPassword);
            //标记测试完成
            isTestConnCompleted = true;

            if (strMsg == null)// 连接成功时，保存配置信息
            {
                // 标记测试成功
                isTestConnApproved = true;
            }
            else// 连接不成功时，提示连接错误
            {
                MessageBox.Show(strMsg);
            }
        }


        /// <summary>
        /// 刷进度条 定时事件
        /// </summary>
        private void timer1_Tick(object sender, EventArgs e)
        {
            iTimerCount++;
            if (isTestConnApproved)// 如果测试连接成功
            {
                // 进度条直接加满
                progressBarTestConnication.Value = progressBarTestConnication.Maximum;
                // 延迟效果
                System.Threading.Thread.Sleep(100);
                // 测试连接完成
                TestConnCompleted();
                // 保存配置信息
                SaveConnConfig();
            }
            else if (isTestConnCompleted)// 测试完成时
            {
                //测试连接完成
                TestConnCompleted();
            }

            // 不让进度条长满
            if (progressBarTestConnication.Value < 80)
            {
                progressBarTestConnication.Value = iTimerCount / 50;
            }
        }

        /// <summary>
        /// 测试连接完成回调方法
        /// </summary>
        private void TestConnCompleted()
        {
            // 隐藏,置零 连接进度条
            progressBarTestConnication.Visible = false;
            progressBarTestConnication.Value = 0;

            iTimerCount = 0;
            // 重置测试连接状态
            isTestConnApproved = false;
            // 重置此时连接完成
            isTestConnCompleted = false;
            // 终止定时器
            timer1.Enabled = false;
            // 启用按钮
            groupBox1.Enabled = true;
        }

        /// <summary>
        /// 保存服务器配置
        /// </summary>
        private void SaveConnConfig()
        {
            // 检查该服务是否已在配置列表中
            DataRow[] drsServer = dtGlobalServer.Select("Server='" + strServer + "'");
            if (drsServer != null && drsServer.Length != 0)
            {   // 已存在,更新用户名和密码,标记存在
                //drsServer[0]["Server"] = strServer;
                drsServer[0]["UserID"] = strUserID;
                drsServer[0]["Password"] = strPassword;
            }
            else
            {   // 不存在时，添加新纪录
                DataRow drGlobalServer = dtGlobalServer.NewRow();
                {
                    drGlobalServer["Server"] = strServer;
                    drGlobalServer["UserID"] = strUserID;
                    drGlobalServer["Password"] = strPassword;
                }
                dtGlobalServer.Rows.Add(drGlobalServer);
            }


            // 保存到配置文件
            try
            {
                XmlHelper.SaveConnConfig(dtGlobalServer);
                //更新表单数据
                //dgvServer.DataSource = dtGlobalServer;
                MessageBox.Show("保存成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }




        private void FrmServer_Load(object sender, EventArgs e)
        {
            //检查配置文件
            XmlHelper.CheckConfigExist();

            //加载服务器配置
            XmlHelper.FillConnConfig(dtGlobalServer);//dtGlobalServer = XmlHelper.LoadConfig(SyncType.Server);
            //绑定配置到表单
            cbxServer.DataSource = dtGlobalServer;
            cbxServer.DisplayMember = "Server";
            cbxServer.ValueMember = "Server";
            cbxServer.Text = "";
            cbxServer.SelectedIndexChanged += new System.EventHandler(this.cbxServer_SelectedIndexChanged);
        }
        // 绑定 服务器对应的 数据库
        private void cbxServer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbxServer.SelectedIndex > -1)
            {
                //设置用户名和密码
                txtUserID.Text = dtGlobalServer.Rows[cbxServer.SelectedIndex]["UserID"].ToString();
                txtPassword.Text = Cryptogram.Decrypt(dtGlobalServer.Rows[cbxServer.SelectedIndex]["Password"].ToString());
            }
            if (txtUserID.Text.Trim() == string.Empty)
            {
                txtUserID.Text = "sa";
            }
        }

    }
}

